package com.gitee.wsl.doc.prosemirror.state.command

import com.gitee.wsl.doc.prosemirror.state.Command
import com.gitee.wsl.doc.prosemirror.state.CommandDispatch
import com.gitee.wsl.doc.prosemirror.state.EditorState

/**
 * 如果选择位于类型规范中具有 truthy `code` 属性的节点中，将选择替换为换行符
 * @param state 编辑器状态
 * @param dispatch 事务处理回调函数
 * @return 操作是否成功执行
 */
object NewlineInCode: Command {
    override fun exec(
        state: EditorState,
        dispatch: CommandDispatch?,
    ): Boolean {
        val head = state.selection._head
        val anchor = state.selection._anchor

        // 检查父节点是否为代码类型且选择在同一父节点内
        if (!head.parent.type.spec.code || !head.sameParent(anchor)) {
            return false
        }

        if (dispatch != null) {
            dispatch(state.tr.insertText("\n").scrollIntoView())
        }

        return true
    }
}

val Command.Companion.newlineInCode get() = NewlineInCode
